package com.example.androideventdistribution.page1

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.view.NestedScrollingChild
import androidx.core.view.NestedScrollingChildHelper
import androidx.recyclerview.widget.RecyclerView


/**
 * Created by YuanWei1 on 2024/6/7.
 *
 * Description:
 */
class InnerRecyclerView : RecyclerView, NestedScrollingChild {
    private val parentScrollConsumed = IntArray(2)
    private val parentOffsetInWindow = IntArray(2)
    private var lastY = 0

    constructor(context: Context?) : super(context!!) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context!!, attrs, defStyle) {
        init()
    }

    private fun init() {
        isNestedScrollingEnabled = true
    }

    override fun onTouchEvent(e: MotionEvent): Boolean {
        when (e.action) {
            MotionEvent.ACTION_DOWN -> {
                lastY = e.rawY.toInt()
                startNestedScroll(SCROLL_AXIS_VERTICAL)
            }

            MotionEvent.ACTION_MOVE -> {
                val y = e.rawY.toInt()
                var dy = lastY - y
                lastY = y

                if (dispatchNestedPreScroll(0, dy, parentScrollConsumed, parentOffsetInWindow)) {
                    dy -= parentScrollConsumed[1]
                }
                if (dy != 0) {
                    scrollBy(0, dy)
                }
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> stopNestedScroll()
        }
        return super.onTouchEvent(e)
    }

    override fun scrollTo(x: Int, y: Int) {
        var y = y
        if (y < 0) {
            y = 0
        }
        super.scrollTo(x, y)
    }

    override fun startNestedScroll(axes: Int): Boolean {
        return getNestedScrollingChildHelper().startNestedScroll(axes)
    }

    override fun stopNestedScroll() {
        getNestedScrollingChildHelper().stopNestedScroll()
    }

    override fun hasNestedScrollingParent(): Boolean {
        return getNestedScrollingChildHelper().hasNestedScrollingParent()
    }

    override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?): Boolean {
        return getNestedScrollingChildHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow)
    }

    override fun dispatchNestedScroll(
        dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int,
        offsetInWindow: IntArray?
    ): Boolean {
        return getNestedScrollingChildHelper().dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,
            offsetInWindow)
    }

    private fun getNestedScrollingChildHelper(): NestedScrollingChildHelper {
        return NestedScrollingChildHelper(this)
    }
}
